<script lang="ts" setup>
import type { Chapter } from '@/types/request';
import { message } from 'ant-design-vue';

defineProps<{
  current: number
  chapters: Chapter[]
}>()
// 修改父组件数据
const emits = defineEmits<{
  (e: 'update:current', value: number): void
  (e: 'update:chapters', value: Chapter[]): void
}>()





/**
 * 章处理的逻辑
 */
// 章集初始数据
const chapters = ref<Chapter[]>([]);

// 创建初始章
function createChapter() {
  chapters.value.push({
    title: '请修改为自己的标题',
    ordered: chapters.value.length,
    episodeList: [],
  });
}
// 初始创建第一章
createChapter();

// 编辑章标题
function editChapterTitle(index: number, value: string) {
  chapters.value[index].title = value;
}
// 删除章
function delChapter(index: number) {
  if (index === 0) {
    message.warn('不可删除第一章节');
    return;
  }else if (chapters.value.length > index + 1) {
    message.warn('请先删除最后一章');
    return;
  }
  chapters.value.splice(index, 1);
}




/**
 * 集处理逻辑
 */
// 创建集
function createEpisode(chapterIndex: number) {
  chapters.value[chapterIndex].episodeList.push({
    chapterId: chapterIndex,
    title: '请修改为自己的标题',
    ordered: chapters.value[chapterIndex].episodeList.length,
  });
}

// 编辑集标题
function editEpisodeTitle(
  chapterIndex: number,
  index: number,
  value: string
) {
  chapters.value[chapterIndex].episodeList[index].title = value;
}

// 删除集
function delEpisode(chapterIndex: number, index: number) {
  chapters.value[chapterIndex].episodeList.splice(index, 1);
}



// 上一步按钮
function handlePrev() {
  emits('update:current', 0)
}

// 下一步按钮
function handleNext() {
  if (chapters.value[0].episodeList.length === 0) {
    message.warn('请至少填写一个以上的集数')
    return
  }
  emits('update:current', 2)
  emits('update:chapters', chapters.value)
}
</script>

<template>
  <div>
    <div ml-auto flex justify-end>
      <a-button type="primary" mb @click="createChapter()" style="background-color:#1677ff">新增章</a-button>
    </div>
    <Chapter v-for="(chapter, idx) in chapters" :key="idx" :index="chapter.ordered" :title="chapter.title"
      :expand-init="idx < 3" @edit-chapter="editChapterTitle" @add-episode="createEpisode" @del-chapter="delChapter" mb>
      <Episode v-for="(episode, subIdx) in chapter.episodeList" :key="subIdx" :index="subIdx" :title="episode.title"
        :chapter-index="idx" @del-episode="delEpisode" @edit-episode="editEpisodeTitle" />
    </Chapter>
    <div flex justify-end gap-2 mt-8>
      <a-button @click="handlePrev" style="background-color:#1677ff">上一步</a-button>
      <a-button type="primary" @click="handleNext" style="background-color:#1677ff">下一步</a-button>
    </div>
  </div>
</template>
